package luafrontend.tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Program which compensates for the missing JastAdd imports (impossible to add through
 * JastAdd program options).
 */
public class ImportInserter {
	public static void main(String[] args) throws IOException {
		final String addedImport = "import " + args[0] + ";";
		final File currentDir = new File(".");
		
		for (File file : currentDir.listFiles()) {
			if (!file.getName().endsWith(".java")) {
				continue;
			}
			
			final File renamedFile = new File(file.getName() + ".old");
			file.renameTo(renamedFile);
			
			final BufferedReader reader = new BufferedReader(new FileReader(renamedFile));
			final BufferedWriter writer = new BufferedWriter(new FileWriter(file));
			
			boolean sawPackage = false;
			for (String line = reader.readLine(); line != null; line = reader.readLine()) {
				writer.write(line);
				writer.newLine();
				
				if (!sawPackage && line.startsWith("package")) {
					sawPackage = true;
					writer.write(addedImport);
					writer.newLine();
				}
			}
			
			reader.close();
			writer.close();
			
			renamedFile.delete();
		}
	}
}
